package com.sunday.fangbeibei.activity;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.reflect.TypeToken;
import com.loopj.android.http.RequestParams;
import com.sunday.fangbeibei.R;
import com.sunday.fangbeibei.cache.ApplicationCache;
import com.sunday.fangbeibei.constants.ApplicationConstants;
import com.sunday.fangbeibei.http.HttpResponseInterface;
import com.sunday.fangbeibei.http.HttpTool;
import com.sunday.fangbeibei.orm.BaseResult;
import com.sunday.fangbeibei.orm.UserInfo;

/**
 * 注册
 * @author 晨曦
 *
 */
public class RegisterActivity extends BaseActivity implements OnClickListener,HttpResponseInterface{

	private EditText name;
	private EditText phone;
	private EditText pwd;
	private EditText repwd;
	private EditText verifycode;
	private EditText number;
	
	private String userName;
	private String telephone;
	private String verify;
	private String password;
	
	
	private UserInfo info;
	
	private CheckBox checkbox;
	
	private TextView verifytv;
	private TextView toast;
	
	private long lastVerify;
	
	private int current;
	
	private View[] views=new View[4];
	
	private boolean flag;//标记
	
	@Override
	protected void createActivity(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		LayoutInflater inflater=LayoutInflater.from(mContext);
		views[0]=inflater.inflate(R.layout.register_one, null);
		views[1]=inflater.inflate(R.layout.register_two, null);
		views[2]=inflater.inflate(R.layout.register_three, null);
		views[3]=inflater.inflate(R.layout.register_four, null);
		
		flag=getIntent().getBooleanExtra("flag", false);
		if(flag){
			loadview(4);
		}else{
			loadview(1);
		}
	}

	private void loadview(int pos){
		current=pos;
		setContentView(views[pos-1]);
		if(pos==1){
			TextView title=(TextView) findViewById(R.id.title);
			title.setText("注册");
			ImageView back=(ImageView) findViewById(R.id.back);
			
			name=(EditText) findViewById(R.id.name);
			phone=(EditText) findViewById(R.id.phone);
			TextView btn1=(TextView) findViewById(R.id.btn1);
			checkbox=(CheckBox) findViewById(R.id.checkbox);
			
			back.setOnClickListener(this);
			btn1.setOnClickListener(this);
			
		}else if(pos==2){
			TextView btn2=(TextView) findViewById(R.id.btn2);
			TextView title=(TextView) findViewById(R.id.title);
			title.setText("注册");
			ImageView back=(ImageView) findViewById(R.id.back);
			verifycode=(EditText) findViewById(R.id.verifycode);
			
			verifytv=(TextView) findViewById(R.id.verify);
			toast=(TextView) findViewById(R.id.toast);
			toast.setText("验证码已发送至"+telephone.substring(0, 3)+"****"+telephone.substring(telephone.length()-4));
			
			verifytv.setOnClickListener(this);
			back.setOnClickListener(this);
			btn2.setOnClickListener(this);
		}else if(pos==3){
			TextView btn3=(TextView) findViewById(R.id.btn3);
			TextView title=(TextView) findViewById(R.id.title);
			title.setText("注册");
			ImageView back=(ImageView) findViewById(R.id.back);
			pwd=(EditText) findViewById(R.id.pwd);
			repwd=(EditText) findViewById(R.id.repwd);
			back.setOnClickListener(this);
			btn3.setOnClickListener(this);
		}else if(pos==4){
			TextView btn4=(TextView) findViewById(R.id.btn4);
			TextView btn5=(TextView) findViewById(R.id.btn5);
			TextView title=(TextView) findViewById(R.id.title);
			number=(EditText) findViewById(R.id.number);
			title.setText("绑定门店码");
			ImageView back=(ImageView) findViewById(R.id.back);
			back.setOnClickListener(this);
			btn4.setOnClickListener(this);
			btn5.setOnClickListener(this);
		}
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch(v.getId()){
		case R.id.back:
			if(current==1||current==4){
				finish();
			}else {
				loadview(current-1);
			}
			break;
		case R.id.btn1:
			if(!checkbox.isChecked()){
				Toast.makeText(mContext, "请同意用户协议！", Toast.LENGTH_SHORT).show();
				break;
			}
			userName=name.getText().toString();
			telephone=phone.getText().toString();
			
			if(userName.equals("")){
				Toast.makeText(mContext, "请输入用户名！", Toast.LENGTH_SHORT).show();
			}
			
			Pattern p = Pattern.compile("^[1][3,4,5,8][0-9]{9}$"); // 验证手机号  
			Matcher m = p.matcher(telephone);  
	        if(m.matches()){
	        	//获取验证码的http请求
	        	show("");
				RequestParams param=new RequestParams();
				param.add("mobile", telephone);
				HttpTool.HttpPost(0, mContext, ApplicationConstants.SERVER_URL+"/mobi/account/sendActiveCode", param, this, new TypeToken<BaseResult>() {
				}.getType());
	        }else{
	        	Toast.makeText(mContext, "请输入正确的手机号！", Toast.LENGTH_SHORT).show();
	        	return;
	        } 
			
			break;
		case R.id.btn2:
			verify=verifycode.getText().toString();
			loadview(3);
			break;
		case R.id.btn3:
			show("");
			RequestParams params=new RequestParams();
			params.add("mobi", telephone);
			params.add("name", userName);
			params.add("nickname", "");
			params.add("password", pwd.getText().toString());
			params.add("rePassword", repwd.getText().toString());
			params.add("activeCode", verify);
			HttpTool.HttpPost(1, mContext, ApplicationConstants.SERVER_URL+"/mobi/account/reg", params, this, new TypeToken<BaseResult<UserInfo>>() {
			}.getType());
			break;
		case R.id.btn4:
			show("");
			RequestParams params2=new RequestParams();
			if(info==null&&!flag){
				return;
			}
			if(flag){
				params2.add("userId", ApplicationCache.INSTANCE.getUserInfo().getId());
			}else{
				params2.add("userId", info.getId());
			}
			
			params2.add("code", number.getText().toString());
			HttpTool.HttpPost(2, mContext, ApplicationConstants.SERVER_URL+"/mobi/account/bind", params2, this, new TypeToken<BaseResult>() {
			}.getType());
			break;
		case R.id.btn5:
			//finish();直接去首页
			goHome();
			break;
		case R.id.verify:
			if((System.currentTimeMillis()-lastVerify)<=60*1000){
				return;
			}
			show("");
			RequestParams param=new RequestParams();
			param.add("mobile", telephone);
			HttpTool.HttpPost(0, mContext, ApplicationConstants.SERVER_URL+"/mobi/account/sendActiveCode", param, this, new TypeToken<BaseResult>() {
			}.getType());
			break;
		}
	}

	@Override
	public void onResponse(int requsetCode, boolean resultStatus, Object result) {
		// TODO Auto-generated method stub
		disMiss();
		switch(requsetCode){
		case 0:
			if(resultStatus){
				lastVerify=System.currentTimeMillis();
				Toast.makeText(mContext, "验证码已发送至您的手机，请注意查收!", Toast.LENGTH_SHORT).show();
				loadview(2);
				VerifyCheck check=new VerifyCheck();
				check.start();
			}else{
				BaseResult re=(BaseResult) result;
				switch(re.getCode()){
				case -1:
					Toast.makeText(mContext, "系统异常！", Toast.LENGTH_SHORT).show();
					break;
				case -2:
					Toast.makeText(mContext, "该号码已被注册！", Toast.LENGTH_SHORT).show();
					break;
				}
			}
			break;
		case 1:
			BaseResult<UserInfo> re=(BaseResult<UserInfo>) result;
			info=re.getResult();
			if(resultStatus){
				password=pwd.getText().toString();
				Toast.makeText(mContext, "注册成功!", Toast.LENGTH_SHORT).show();
				loadview(4);
			}else{
				switch(re.getCode()){
				case -1:
					Toast.makeText(mContext, "系统异常！", Toast.LENGTH_SHORT).show();
					break;
				case -2:
					Toast.makeText(mContext, "该账号已被注册！", Toast.LENGTH_SHORT).show();
					break;
				case -3:
					Toast.makeText(mContext, "两次密码不一致！", Toast.LENGTH_SHORT).show();
				case -4:
					Toast.makeText(mContext, "验证码错误！", Toast.LENGTH_SHORT).show();
					break;
				}
			}
			break;
		case 2:
			if(resultStatus){
				Toast.makeText(mContext, "绑定成功,请等待门店负责人审核通过!", Toast.LENGTH_SHORT).show();
				goHome();
			}else{
				BaseResult res=(BaseResult) result;
				switch(res.getCode()){
				case -1:
					Toast.makeText(mContext, "系统异常！", Toast.LENGTH_SHORT).show();
					break;
				case -2:
					Toast.makeText(mContext, "没有对应的门店！", Toast.LENGTH_SHORT).show();
					break;
				}
			}
			break;
		}
	}

	@Override
	public void onFailure() {
		// TODO Auto-generated method stub
		disMiss();
	}
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		if (keyCode == KeyEvent.KEYCODE_BACK
				&& event.getAction() == KeyEvent.ACTION_DOWN) {
				
			if(current==1||current==4){
				finish();
			}else {
				loadview(current-1);
			}
			return true;
		}
		return true;
	}


	private void goHome(){
		
		if(info==null&&!flag){
			return;
		}
		if(!flag){
			SharedPreferences settings = getSharedPreferences("fbb", 0);
			SharedPreferences.Editor editor = settings.edit();
			editor.putString("name", telephone);
			editor.putString("password", password);
			
			//editor.putString("userinfo", new Gson().toJson(result0.getResult()));
			
			editor.commit();
			
			ApplicationCache.INSTANCE.setUserInfo(info);
		}
		Intent in=new Intent(mContext, HomeActivity.class);
		startActivity(in);
		
	}
	


	class VerifyCheck extends Thread{

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			while(System.currentTimeMillis()-lastVerify<=60*1000){
				runOnUiThread(updateVerify);
				try {
					sleep(1000);
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}
			
			runOnUiThread(new Runnable() {
				
				@Override
				public void run() {
					// TODO Auto-generated method stub
					verifytv.setText("重新获取验证码");
				}
			});
		}
		
	};
	

	Runnable updateVerify=new Runnable() {
		
		@Override
		public void run() {
			// TODO Auto-generated method stub
			if(verifytv!=null){
				verifytv.setText(60-(System.currentTimeMillis()-lastVerify)/1000+"秒后重新获取");
			}
		}
	};
}
